package com.wyx.Controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wyx.Common.R;
import com.wyx.DTO.DishDto;
import com.wyx.Pojo.Category;
import com.wyx.Pojo.Dish;
import com.wyx.Pojo.DishFlavor;
import com.wyx.Service.CategoryService;
import com.wyx.Service.DishService;
import com.wyx.Service.DishflavorService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 菜品模块
 */
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishflavorService dishflavorService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;

    //返回菜品列表
//    @Cacheable(value = "DishCache",key = "#dish.categoryId")
    @GetMapping("/list")
    public R<List<DishDto>> getlist(Dish dish) {
        //菜品的key
        String key= "dish_"+dish.getCategoryId();
        //查看redis有无缓存到该品种的菜品
        List<DishDto>res= (List<DishDto>) redisTemplate.opsForValue().get(key);
        System.out.println(res);
        //如果有则返回
        if (res!=null){
            return R.success(res);
        }

        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        //如果名称没有的话就不查询
        if (dish.getName() == null) {
            wrapper.eq(Dish::getCategoryId, dish.getCategoryId());
            wrapper.eq(Dish::getStatus, 1);
            List<Dish> list = dishService.list(wrapper);
            List<DishDto>dishDtoList=new ArrayList<>();
            for (Dish everyDish : list) {
                DishDto dishDto=new DishDto();
                //将dish里面的值复制到Dishdto里面
                BeanUtils.copyProperties(everyDish,dishDto);
                //货期菜品的id
                Long dishId = everyDish.getId();
                //根据菜品id查询对应的口味
                LambdaQueryWrapper<DishFlavor>wrapper1=new LambdaQueryWrapper<>();
                wrapper1.eq(DishFlavor::getDishId,dishId);
                List<DishFlavor> dishFlavorList = dishflavorService.list(wrapper1);
                dishDto.setFlavors(dishFlavorList);
                dishDtoList.add(dishDto);
            }
            redisTemplate.opsForValue().set(key,dishDtoList,60,TimeUnit.MINUTES);
            return R.success(dishDtoList);
        } else {
            wrapper.like(Dish::getName, dish.getName());
            wrapper.eq(Dish::getStatus, 1);
            List<Dish> list = dishService.list(wrapper);
            List<DishDto>dishDtoList=new ArrayList<>();
            for (Dish dish1 : list) {
                DishDto dishDto=new DishDto();
                BeanUtils.copyProperties(dish1,dishDto);
                dishDtoList.add(dishDto);
            }
            redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);
            return R.success(dishDtoList);
        }
        //将启售的筛选出来
    }

    /**
     * 服务端：新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> addnewdish(@RequestBody DishDto dishDto) {
        dishService.addnewdish(dishDto);
        //清理相对应的缓存数据
        String categoryId = String.valueOf(dishDto.getCategoryId());
        String key= "dish_"+categoryId;
        redisTemplate.delete(key);
        return R.success("新增菜品成功~");
    }

    /**
     * 服务端数据：菜品分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> getDishPage(int page, int pageSize, String name) {

        Page<Dish> page1 = new Page<>(page, pageSize);
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name!= null, Dish::getName, name);
//        wrapper.orderByDesc(Dish::getUpdateTime);
        Page<DishDto> res = new Page<>();
        List<DishDto> reslist = new ArrayList<>();
        //查询dish
        dishService.page(page1, wrapper);

        //对象拷贝 但record不拷贝
        BeanUtils.copyProperties(page1, res, "records");
        List<Dish> records = page1.getRecords();
        for (Dish record : records) {
            //获取当前dish的id 根据id查找到Categoryname
            Category byId = categoryService.getById(record.getCategoryId());
            String categoryName = byId.getName();
            DishDto newdishDto = new DishDto();
            newdishDto.setCategoryName(categoryName);
            //将record复制到DishDto里面去
            BeanUtils.copyProperties(record, newdishDto);

            reslist.add(newdishDto);
        }
        res.setRecords(reslist);
        return R.success(res);
    }

    /**
     * 服务端：根据ID会显数据
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> getone(@PathVariable Long id) {
        Dish byId = dishService.getById(id);
        List<DishFlavor> dishFlavors = dishflavorService.getbyDishId(id);
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(byId, dishDto);
        dishDto.setFlavors(dishFlavors);
        return R.success(dishDto);
    }

    /**
     * 服务端：修改某个菜品信息
     *
     * @param dishDto
     * @return
     */
//    @CacheEvict(value = "DishCache",key = "#dishDto.categoryId")
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        dishService.updatewithFlavor(dishDto);
        //删除缓存

        String key= "dish_"+dishDto.getCategoryId();
        redisTemplate.delete(key);
        return R.success("修改成功");
    }

    /**
     * 服务端：批量删除
     *
     * @param ids
     * @return
     */
//    @CacheEvict(value = "DishCache",allEntries = true)
    @DeleteMapping
    public R<String> deletebyIDS(Long[] ids) {
//        List<Long> objects = (List<Long>) CollectionUtils.arrayToList(ids);
////        for (Long id : ids) {
////            //清理缓存
////            String id1= String.valueOf(id);
////            redisTemplate.delete(id1);
////        }
        for (Long id : ids) {
            Dish byId = dishService.getById(id);
            //删除缓存
            String key="dish_"+byId.getCategoryId();
            redisTemplate.delete(key);
            //删除数据
            dishService.removeById(id);

        }
        return R.success("删除成功~");
    }

    /**
     * 修改状态1
     *
     * @param ids
     * @return
     */
//    @CacheEvict(value = "DishCache",allEntries = true)
    @PostMapping("/status/1")
    public R<String> upStatus(String[] ids) {
        dishService.updateStatus(ids);
        return R.success("修改成功");
    }

    /**
     * 修改状态0
     *
     * @param ids
     * @return
     */
//    @CacheEvict(value = "DishCache",allEntries = true)
    @PostMapping("/status/0")
    public R<String> offStatus(String[] ids) {
        System.out.println(Arrays.toString(ids));
        for (String id : ids) {
            Dish byId = dishService.getById(id);
            byId.setStatus(0);
            dishService.updateById(byId);
            //清理缓存
            redisTemplate.delete("dish_"+byId.getCategoryId());
        }
        return R.success("修改成功");
    }
}
